<template>
  <div class="main-content">
    <el-card class="person-card">
      <div class="header-actions">
        <el-button type="primary" @click="updatePassword" icon="el-icon-lock">修改密码</el-button>
      </div>
      
      <el-form :model="user" label-width="80px" class="person-form">
        <div class="avatar-container">
          <el-upload
              class="avatar-uploader"
              :action="$baseUrl + '/files/upload'"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
          >
            <img v-if="user.avatar" :src="user.avatar" class="avatar" />
            <div v-else class="avatar-placeholder">
              <i class="el-icon-plus"></i>
              <div class="upload-text">上传头像</div>
            </div>
          </el-upload>
        </div>

        <div class="form-content">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="user.username" placeholder="学号" disabled></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="realName">
            <el-input v-model="user.realName" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="user.phone" placeholder="请输入电话号码"></el-input>
          </el-form-item>
          <el-form-item label="宿舍号" prop="dormnum">
            <el-input v-model="user.dormnum" placeholder="请输入宿舍号"></el-input>
          </el-form-item>
        </div>

        <div class="form-actions">
          <el-button type="primary" @click="update" icon="el-icon-check">保存信息</el-button>
        </div>
      </el-form>
    </el-card>
    <el-dialog title="修改密码" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="user" label-width="80px" style="padding-right: 20px" :rules="rules" ref="formRef">
        <el-form-item label="新密码" prop="newPassword">
          <el-input show-password v-model="user.newPassword" placeholder="新密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input show-password v-model="user.confirmPassword" placeholder="确认密码"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="fromVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请确认密码'))
      } else if (value !== this.user.newPassword) {
        callback(new Error('确认密码错误'))
      } else {
        callback()
      }
    }
    return {
      user: {  // 预先定义所有响应式字段
        id: null,
        username: '',
        realName: '',
        phone: '',
        dormnum: '',
        avatar: '',
        newPassword: '',
        confirmPassword: ''
      },
      dialogVisible: false,
      rules: {
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
        ],
        confirmPassword: [
          { validator: validatePassword, required: true, trigger: 'blur' },
        ],
      }
    }
  },
  created() {
    // 合并本地存储数据
    const localUser = JSON.parse(localStorage.getItem('xm-user') || '{}')
    Object.assign(this.user, localUser)
    
    // 获取用户信息
    this.$request.get('/userInfo/selectById/'+this.user.id).then(res => {
      if (res.code === '200') {
        // 确保字段名称匹配，这里假设接口返回字段与前端定义一致
        this.user = {
          ...this.user,
          realName: res.data.realName,
          phone: res.data.phone,
          dormnum: res.data.dormnum
        }
      }
    })
  },
  methods: {
    update() {
      // 保存当前的用户信息到数据库
      this.$request.post('/userInfo/update', this.user).then(res => {
        if (res.code === '200') {
          // 成功更新
          this.$message.success('保存成功')
          // 更新浏览器缓存里的用户信息
          localStorage.setItem('xm-user', JSON.stringify(this.user))

          // 触发父级的数据更新
          this.$emit('update:user')
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handleAvatarSuccess(response, file, fileList) {
      // 把user的头像属性换成上传的图片的链接
      this.$set(this.user, 'avatar', response.data)
    },
    // 修改密码
    updatePassword() {
      this.dialogVisible = true
    },
    save() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.$request.post('/updatePassword', this.user).then(res => {
            if (res.code === '200') {
              // 成功更新
              this.$message.success('修改密码成功')
              this.$router.push('/login')
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.main-content {
  min-height: 77.3vh;
  background-color: #f5f7fa;
  padding: 20px;
}

.person-card {
  width: 600px;
  margin: 0 auto;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.header-actions {
  text-align: right;
  margin-bottom: 30px;
}

.person-form {
  padding: 0 20px;
}

.avatar-container {
  text-align: center;
  margin-bottom: 40px;
}

.avatar-uploader .el-upload {
  border: 2px dashed #e4e7ed;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
  transform: translateY(-2px);
}

.avatar-placeholder {
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
  border-radius: 50%;
  background-color: #f5f7fa;
}

.avatar-placeholder i {
  font-size: 28px;
  color: #909399;
}

.upload-text {
  font-size: 14px;
  color: #909399;
  margin-top: -20px;
}

.avatar {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  object-fit: cover;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.form-content {
  max-width: 400px;
  margin: 0 auto;
}

.form-actions {
  text-align: center;
  margin: 40px 0 20px;
}

.el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.el-input {
  transition: all 0.3s;
}

.el-input:hover {
  transform: translateX(5px);
}

.el-button {
  padding: 12px 25px;
  font-weight: 500;
}
</style>